//
//  UPAuthViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/25.
//

#import "UPAuthViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UPAuthCompletedViewController.h"
#import "UPIdentityInformationView.h"
#import "UPCalenderCustomView.h"

@interface UPAuthViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate, UPCalenderCustomViewDelegate>

@property (nonatomic, strong) UIImageView *containerImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIImageView *prcImageView;
@property (nonatomic, strong) UIImageView *faceImageView;
@property (nonatomic, strong) UILabel *prcLabel;
@property (nonatomic, strong) UILabel *faceLabel;
@property (nonatomic, strong) UILabel *goLabel;
@property (nonatomic, strong) UIButton *prcGoButton;
@property (nonatomic, strong) UIButton *faceGoButton;
@property (nonatomic, strong) UIButton *continueButton;
@property (nonatomic, strong) UIButton *prcBgButton;
@property (nonatomic, strong) UIButton *faceBgButton;
@property (nonatomic, assign) AuthImagePickerType imagePickerType;
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@property (nonatomic, strong) UPCustomAlertView *idAlert;
@property (nonatomic, strong) UPCustomAlertView *calendarAlert;
@property (nonatomic, strong) UPIdentityInformationView *identityInformationView;

@property (nonatomic, assign) double startTime;

@end

@implementation UPAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imagePickerType = AuthImagePickerTypePRC;
    [self commonInitSubviews];
    [self fetchAuthInfo];
    self.startTime = [[NSDate date] timeIntervalSince1970];

//    AuthLapidant *l = [[AuthLapidant alloc] init];
//    l.quindecimlocalety = @"//";
//    l.assumeization = @"//";
//    l.movieion = @"//";
//    [self showIdentifyInfoAlert:l];
}

- (void)fetchAuthInfo {
    [SVProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchAuthenticationWithProductId:self.currentOmniosity.degreeaneous completion:^(IdentityVerificationModel * _Nonnull model, NSString * _Nonnull msg) {
        if (model) {
            [weakSelf updateSubviewsWithModel:model];
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchUploadData:(NSData *)data {
    if (self.imagePickerType == AuthImagePickerTypeUnknow) {
        return;
    }
    [SVProgressHUD show];
    __block typeof(self) weakSelf = self;
    double startTime = [[NSDate date] timeIntervalSince1970];
    [UPStocksAPIManager fetchUploadWithImageData:data imageType:self.imagePickerType completion:^(AuthLapidant * _Nonnull model, NSString * _Nonnull msg) {
        if (model) {
            [SVProgressHUD dismiss];
            if (self.imagePickerType == AuthImagePickerTypePRC) {
                [weakSelf showIdentifyInfoAlert: model];
            } else {
                [weakSelf updateSubviewsWithPRCFinish:YES faceFinish:YES];
                NSDictionary *dic = @{
                    @"followUpData": self.currentOmniosity
                };
                [[NSNotificationCenter defaultCenter] postNotificationName:kFollowUpMyOrderKey
                                                                    object:nil
                                                                  userInfo:dic];
                [UPReportDataManager reportToMaiDian:UPSceneTypeFaceCredential
                                           productId:self.currentOmniosity.degreeaneous
                                          productNum:self.currentOmniosity.viciacity
                                      startTimeStamp:startTime
                                        endTimeStamp:[[NSDate date] timeIntervalSince1970]];
            }
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchSaveIdentifyInfoWithName:(NSString *)name idNum:(NSString *)idNum birthday:(NSString *)birthday {
    
    if (name == nil || name.length == 0 || [name isEqualToString:@"//"]) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"Aadhaar Name")];
        return;
    }
    
    if (idNum == nil || idNum.length == 0 || [idNum isEqualToString:@"//"]) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"Aadhaar Number")];
        return;
    }
    
    if (birthday == nil || birthday.length == 0 || [birthday isEqualToString:@"//"]) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"Birthday")];
        return;
    }
    
    NSString *productId = self.currentOmniosity.degreeaneous ?: @"";
    NSString *productNum = [NSString stringWithFormat:@"%@", self.currentOmniosity.viciacity];
    [SVProgressHUD show];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchSaveIdentifyInfoWithName:name idNum:idNum birthday:birthday productId:productId productNum:productNum completion:^(BOOL success, NSString *msg) {
        if (success) {
            [weakSelf.idAlert dismiss];
            [SVProgressHUD dismiss];
            [UPReportDataManager reportToMaiDian:UPSceneTypeIdCredential
                                       productId:productId
                                      productNum:productNum
                                  startTimeStamp:self.startTime
                                    endTimeStamp:[[NSDate date] timeIntervalSince1970]];
            [weakSelf updateSubviewsWithPRCFinish:YES faceFinish:NO];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)updateSubviewsWithModel: (IdentityVerificationModel *)model {
    if (model.cilistyleproof.septuagentic == 1) {
        [self updateSubviewsWithPRCFinish:YES faceFinish:NO];
    } else {
        [self updateSubviewsWithPRCFinish:NO faceFinish:NO];
    }
    
    if (model.successfulfold.septuagentic == 1) {
        [self updateSubviewsWithPRCFinish: YES faceFinish:YES];
    }
}

- (void)updateSubviewsWithPRCFinish: (BOOL)prcFinish faceFinish:(BOOL) faceFinish {
    if (prcFinish) {
        self.prcGoButton.backgroundColor = [UIColor colorWithHexString:@"#73C676"];
        [self.prcGoButton setTitle: LocalizableForKey(@"Completed") forState:UIControlStateNormal];
        self.prcBgButton.enabled = NO;
        self.imagePickerType = AuthImagePickerTypeFace;
    } else {
        self.prcGoButton.backgroundColor = [UIColor colorWithHexString:@"#233446"];
        [self.prcGoButton setTitle: LocalizableForKey(@"GO") forState:UIControlStateNormal];
        self.prcBgButton.enabled = YES;
    }
    
    if (faceFinish) {
        self.faceGoButton.backgroundColor = [UIColor colorWithHexString:@"#73C676"];
        [self.faceGoButton setTitle: LocalizableForKey(@"Completed") forState:UIControlStateNormal];
        self.faceGoButton.enabled = NO;
        self.imagePickerType = AuthImagePickerTypeUnknow;
    } else {
        self.faceGoButton.backgroundColor = [UIColor colorWithHexString:@"#233446"];
        [self.faceGoButton setTitle: LocalizableForKey(@"GO") forState:UIControlStateNormal];
        self.faceGoButton.enabled = YES;
    }
}

- (void)commonInitSubviews {
    
    UIImage *bgImage = [UIImage imageNamed:@"auth_cer_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    [self.containerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(40);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(bgHeight);
        make.width.mas_equalTo(bgWidth);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.containerImageView);
        make.top.equalTo(self.containerImageView).offset(18);
    }];
    
    [self.prcImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.containerImageView).offset(50);
        make.top.equalTo(self.containerImageView).offset(90);
        make.height.mas_equalTo(57);
        make.width.mas_equalTo(100);
    }];
    
    [self.prcLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.prcImageView);
        make.height.mas_equalTo(22);
        make.leading.equalTo(self.prcImageView.mas_trailing).offset(20);
    }];
    
    [self.prcGoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.prcImageView);
        make.height.mas_equalTo(31);
        make.trailing.equalTo(self.view).offset(-26);
    }];
    
    [self.faceImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.prcImageView);
        make.top.equalTo(self.prcImageView).offset(140);
        make.height.mas_equalTo(57);
        make.width.mas_equalTo(100);
    }];
    
    [self.faceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.faceImageView);
        make.height.mas_equalTo(22);
        make.leading.equalTo(self.prcLabel);
    }];
    
    [self.faceGoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.faceImageView);
        make.height.equalTo(self.prcGoButton.mas_height);
        make.leading.equalTo(self.prcGoButton);
    }];

    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style4"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.continueButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerImageView.mas_bottom).offset(35);
        make.centerX.equalTo(self.containerImageView);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
    }];
    
    [self.prcBgButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.containerImageView);
        make.top.equalTo(self.prcImageView).offset(-20);
        make.bottom.equalTo(self.prcImageView).offset(20);
    }];
    
    [self.faceBgButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.containerImageView);
        make.top.equalTo(self.faceImageView).offset(-20);
        make.bottom.equalTo(self.faceImageView).offset(20);
    }];
}

- (UIImageView *)containerImageView {
    if (!_containerImageView) {
        _containerImageView = [[UIImageView alloc] init];
        _containerImageView.contentMode = UIViewContentModeScaleAspectFit;
        _containerImageView.image = [UIImage imageNamed:@"auth_cer_bg"];
        [self.view addSubview:_containerImageView];
    }
    return _containerImageView;
}

- (UIImageView *)prcImageView {
    if (!_prcImageView) {
        _prcImageView = [[UIImageView alloc] init];
        _prcImageView.contentMode = UIViewContentModeScaleAspectFit;
        _prcImageView.image = [UIImage imageNamed:@"auth_prc_id"];
        [self.view addSubview:_prcImageView];
    }
    return _prcImageView;
}

- (UIImageView *)faceImageView {
    if (!_faceImageView) {
        _faceImageView = [[UIImageView alloc] init];
        _faceImageView.contentMode = UIViewContentModeScaleAspectFit;
        _faceImageView.image = [UIImage imageNamed:@"auth_face"];
        [self.view addSubview:_faceImageView];
    }
    return _faceImageView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:15];
        _titleLabel.textColor = [UIColor colorWithHexString:@"#8500FD"];
        _titleLabel.text = LocalizableForKey(@"Certification Items");
        [self.view addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)prcLabel {
    if (!_prcLabel) {
        _prcLabel = [[UILabel alloc] init];
        _prcLabel.textAlignment = NSTextAlignmentCenter;
        _prcLabel.font = [UIFont boldSystemFontOfSize:14];
        _prcLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _prcLabel.text = LocalizableForKey(@"PRC ID");
        [self.view addSubview:_prcLabel];
    }
    return _prcLabel;
}

- (UIButton *)prcGoButton {
    if (!_prcGoButton) {
        _prcGoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _prcGoButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
        [_prcGoButton setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        _prcGoButton.backgroundColor = [UIColor colorWithHexString:@"#233446"];
        [_prcGoButton setTitle: LocalizableForKey(@"GO") forState:UIControlStateNormal];
        _prcGoButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
        _prcGoButton.layer.masksToBounds = YES;
        _prcGoButton.layer.cornerRadius = 11;
        [self.view addSubview:_prcGoButton];
    }
    return _prcGoButton;
}

- (UILabel *)faceLabel {
    if (!_faceLabel) {
        _faceLabel = [[UILabel alloc] init];
        _faceLabel.textAlignment = NSTextAlignmentCenter;
        _faceLabel.font = [UIFont boldSystemFontOfSize:14];
        _faceLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _faceLabel.text = LocalizableForKey(@"Face");
        [self.view addSubview:_faceLabel];
    }
    return _faceLabel;
}

- (UIButton *)faceGoButton {
    if (!_faceGoButton) {
        _faceGoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _faceGoButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
        [_faceGoButton setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
        _faceGoButton.backgroundColor = [UIColor colorWithHexString:@"#233446"];
        [_faceGoButton setTitle: LocalizableForKey(@"GO") forState:UIControlStateNormal];
        _faceGoButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
        _faceGoButton.layer.masksToBounds = YES;
        _faceGoButton.layer.cornerRadius = 11;
        [self.view addSubview:_faceGoButton];
    }
    return _faceGoButton;
}

- (UIButton *)continueButton {
    if (!_continueButton) {
        _continueButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_continueButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style4"] forState: UIControlStateNormal];
        [_continueButton setTitle:LocalizableForKey(@"Continue certification") forState:UIControlStateNormal];
        [_continueButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        _continueButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:400];
        [_continueButton addTarget:self action:@selector(clickContinueButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_continueButton];
    }
    return _continueButton;
}

- (UIButton *)prcBgButton {
    if (!_prcBgButton) {
        _prcBgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_prcBgButton addTarget:self action:@selector(clickPrcButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_prcBgButton];
    }
    return _prcBgButton;
}

- (UIButton *)faceBgButton {
    if (!_faceBgButton) {
        _faceBgButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_faceBgButton addTarget:self action:@selector(clickFaceButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_faceBgButton];
    }
    return _faceBgButton;
}

#pragma mark - Method
- (void)clickPrcButton {
    [self checkCameraPermissionAndPresentPicker];
}

- (void)clickFaceButton {
    [self checkCameraPermissionAndPresentPicker];
}

- (void)clickContinueButton {
    if (self.imagePickerType == AuthImagePickerTypeUnknow) {
        UPAuthCompletedViewController *completedVC = [[UPAuthCompletedViewController alloc] init];
        completedVC.currentOmniosity = self.currentOmniosity;
        completedVC.currentLoanDetailModel = self.currentLoanDetailModel;
        [self.navigationController pushViewController:completedVC animated:YES];
    } else {
        [self checkCameraPermissionAndPresentPicker];
    }
}
#pragma mark - 相机
- (void)checkCameraPermissionAndPresentPicker {
    // 获取当前的授权状态
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    switch (authStatus) {
        case AVAuthorizationStatusAuthorized: {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentCameraPicker];
            });
            break;
        }
        case AVAuthorizationStatusNotDetermined: {
            // 用户尚未做出选择，此时系统会自动弹窗请求权限
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self presentCameraPicker];
                    });
                } else {
                    NSLog(@"用户拒绝了相机权限");
                }
            }];
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted: {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showPermissionAlert];
            });
            break;
        }
    }
}

- (void)presentCameraPicker {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.imagePicker = [[UIImagePickerController alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePicker.allowsEditing = NO; // 可选
        [self presentViewController:self.imagePicker animated:YES completion:nil];
        
        if (self.imagePickerType == AuthImagePickerTypeFace) {
            self.imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self hiddeChangeCameraView: self.imagePicker.view];
            });
        }
    }
}

- (void)hiddeChangeCameraView:(UIView *)cameraView {
    NSString *name = @"CAMFlipButton";
    for (UIView *view in cameraView.subviews) {
        if ([view.description containsString:name]) {
            view.hidden = YES;
            return;
        }
        [self hiddeChangeCameraView:view];
    }
}

// 引导用户去设置的Alert
- (void)showPermissionAlert {
    
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithBackgroundImage:[UIImage imageNamed:@"alert_bg_image1"] style:UPAlertViewStyleBottomSheet];
    [alert setTitle:@"" font:[UIFont boldSystemFontOfSize:13]];

    [alert setContent:LocalizableForKey(@"NSCameraUsageDescription") font:[UIFont systemFontOfSize:13]];
    
    [alert addButtonWithTitle:LocalizableForKey(@"Turning on")
                        style:UPButtonStyleDefault
                      handler:^{
        upOpenAppSettings();
    }];

    [alert addButtonWithTitle:LocalizableForKey(@"Give up")
                        style:UPButtonStyleDestructive
                      handler:^{
    }];

    // 显示弹窗
    [alert showInView:[UIApplication up_currentKeyWindow]];
}

- (void)showIdentifyInfoAlert:(AuthLapidant *)model {
    UPIdentityInformationView *customView = [[UPIdentityInformationView alloc] init];
    customView.model = model;
    UIImage *bgImage = [UIImage imageNamed:@"calendar_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    customView.frame = CGRectMake(0, 0, bgWidth, bgHeight);
    __block typeof(self) weakSelf = self;
    customView.confirmBlock = ^(NSString * _Nonnull name, NSString * _Nonnull idNum, NSString * _Nonnull birthday) {
        [weakSelf fetchSaveIdentifyInfoWithName:name idNum:idNum birthday:birthday];
    };
    
    customView.birthdayBlock = ^(NSString * _Nonnull birthday) {
        [weakSelf.view endEditing:YES];
        [weakSelf showCalendarAlert:[birthday stringConvertToDate]];
    };
    
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithCustomView:customView style:UPAlertViewStyleBottomSheet];
    // 显示弹窗
    [alert showInView:self.view];
    self.idAlert = alert;
    self.identityInformationView = customView;
}

- (void)showCalendarAlert:(NSDate *)date {
    UPCalenderCustomView *customView = [[UPCalenderCustomView alloc] initWithFrame:CGRectZero selectDate:date];
    UIImage *bgImage = [UIImage imageNamed:@"calendar_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    customView.frame = CGRectMake(0, 0, bgWidth, bgHeight);
    customView.delegate = self;
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithCustomView:customView style:UPAlertViewStyleBottomSheet];
    [alert showInView:self.view];
    self.calendarAlert = alert;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    
    UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
    NSData *compressImageData = [chosenImage compressToMaxFileSizeKB:500];
    __block typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if (compressImageData.length > 500 * 1024) {
            [SVProgressHUD showInfoWithStatus:@"failed"];
        } else {
            [weakSelf fetchUploadData:compressImageData];
        }
    }];
}

// 当用户取消拍照时调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    // 直接关闭相机界面
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -UPCalenderCustomViewDelegate
- (void)customCalendarPicker:(UPCalendarPicker *)picker didSelectDate:(NSDate *)date {
    self.identityInformationView.birthdayTextLabel.text = [date dateConvertToString];
    [self.calendarAlert dismiss];
}

@end
